#include <iostream>
using namespace std;
#include <sqlite3.h>
#define BUFFER_SIZE 128
#include "sqliteDataBase.h"
#include <iomanip>

void demoexec(sqlite3 *musicDb) // 插入数据
{
    /* 将数据插入到数据库 */
    string name, passwd;
    printf("请输入你的姓名:");
    cin >> name;
    printf("请输入你的密码:");
    cin >> passwd;
    // const char *sql = "INSERT INTO userInfo (username,passwd) VALUES('zhaoliu','123');";
    const char *sql = "INSERT INTO userInfo (username,passwd) VALUES('%s','%s');";
    char requestSql[BUFFER_SIZE] = {0};

    /* 格式化输入输出 */
    sprintf(requestSql, sql, name.c_str(), passwd.c_str());

    /* 执行sql语句 */
    int ret = sqlite3_exec(musicDb, requestSql, NULL, NULL, NULL);
    if (ret != SQLITE_OK)
    {
        cout << "sqlite exec error:";
        exit(-1);
    }
}

void textSelect(sqlite3 *musicDb)
{
    /* 查询数据 */
    const char *sql = "select * from userInfo;";
    char **result = NULL;
    int rows, columns = 0;
    int ret = sqlite3_get_table(musicDb, sql, &result, &rows, &columns, NULL);
    if (ret != SQLITE_OK)
    {
        cout << "sqlite3 get table error." << endl;
        exit(-1);
    }
    cout << "rows:" << rows << endl;
    cout << "columns:" << columns << endl;

    for (int row = 1; row < rows; row++)
    {
        for (int col = 0; col < columns; col++)
        {
            cout << result[row * columns + col] << "\t";
        }
        cout << endl;
    }
}

int main()
{
#if 0
    const char *dbName = "./music.db";
    /* 数据库的句柄 */
    sqlite3 *musicDb = NULL;

    /* 打开数据库 */
    int ret = sqlite3_open(dbName, &musicDb);
    if (ret != SQLITE_OK)
    {
        cout << "sqlite3 open error." << endl;
        exit(-1);
    }

    /* 插入数据 */
    // demoexec(musicDb);

    /* 查询数据库 */
    // textSelect(musicDb);

    /* 关闭数据库 */
    sqlite3_close(musicDb);
#endif

#if 1

    SqliteDataBase sqliteDB;
    /* 连接数据库 */
    sqliteDB.connectDB("./music.db");
    const char *sql = "INSERT INTO userInfo (username,passwd) VALUES('zzz','999');";

    sql = "select * from userInfo;";
    QueryResult res = sqliteDB.querySql(sql);

    for (int idx = 0; idx < res.columnName.size(); idx++)
    {
        cout << res.columnName[idx] << "\t";
    }
    cout << endl;

    int rows = res.rows.size();
    for (int idx = 0; idx < rows; idx++)
    {
        /* 每一行的数据 */
        vector<string> rowData = res.rows[idx];

        for (int jdx = 0; jdx < rowData.size(); jdx++)
        {
            cout << rowData[jdx] << "      \t";
        }
        cout << endl;
    }
    sqliteDB.close();

#endif

    return 0;
}